﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using CarolLib.Control;
using DispatchAssist.Service;
using System.Web.Services.Protocols;
using System.Collections;

namespace DispatchAssist.AppHost
{
    [ModuleContract("1BF37A1A-7409-4109-829A-D8C5A72E9841", "系统管理", "机型管理")]
    public partial class PlaneTypeManage : MdiUserControl
    {

        #region member
        private AuthService serviceProxy;

        private List<PlaneType> planeList;
        private List<SMSContactGroup> companyList;
        #endregion

        public PlaneTypeManage()
            : base()
        {
            InitializeComponent();
        }

        public PlaneTypeManage(XmlNode node)
            : this()
        {

        }

        #region ovverride
        public override void Onload()
        {
            base.Onload();
            serviceProxy = new AuthService();
            serviceProxy.DASoapHeaderValue = AuthContext.Current.GetSoapHeader();

            BindWebServieSyncMethod();

            DataBind();
        }

        public override void Unload()
        {
            base.Unload();
            serviceProxy = null;
            planeList = null;
            companyList = null;
        }

        private void BindWebServieSyncMethod()
        {
            serviceProxy.GetAllTialsAndTypeCompleted += new GetAllTialsAndTypeCompletedEventHandler(service_GetAllTialsAndTypeCompleted);
            serviceProxy.GetContactGroupCompleted += new GetContactGroupCompletedEventHandler(service_GetContactGroupCompleted);
            serviceProxy.DeletePlaneTypeCompleted += new DeletePlaneTypeCompletedEventHandler(service_DeletePlaneTypeCompleted);
            //   serviceProxy.DeletePlaneTypeCompleted += new DeletePlaneTypeCompletedEventHandler(service_DeletePlaneTypeCompleted);
            serviceProxy.DeletePlaneInfoCompleted += new DeletePlaneInfoCompletedEventHandler(service_DeletePlaneInfoCompleted);
            serviceProxy.InsertPlaneTypeCompleted += new InsertPlaneTypeCompletedEventHandler(service_InsertPlaneTypeCompleted);
            serviceProxy.UpdatePlaneTypeCompleted += new UpdatePlaneTypeCompletedEventHandler(service_UpdatePlaneTypeCompleted);
            serviceProxy.InsertPlaneInfoCompleted += new InsertPlaneInfoCompletedEventHandler(service_InsertPlaneInfoCompleted);
            serviceProxy.UpdatePlaneInfoCompleted += new UpdatePlaneInfoCompletedEventHandler(service_UpdatePlaneInfoCompleted);

        }

        #endregion

        #region customer method

        private void DataBind()
        {
            try
            {
                //AuthService serviceProxy = service;
                serviceProxy.GetAllTialsAndTypeAsync();
            }
            catch (SoapHeaderException soapEx)
            {
                CarolLib.Log.Instance.Error("error in webservice GetAllTialsAndTypeAsync", soapEx);
                MessageBox.Show("网络错误");
            }
            catch (Exception ex)
            {
                CarolLib.Log.Instance.Error("error in webservice GetAllTialsAndTypeAsync", ex);
                MessageBox.Show("未知错误");
            }
        }

        private void service_GetAllTialsAndTypeCompleted(object sender, GetAllTialsAndTypeCompletedEventArgs e)
        {
            try
            {
                planeList = e.Result.ToList<PlaneType>();

                serviceProxy.GetContactGroupAsync();


                CreateTreeNode(planeList);

                BindParentDDL();
            }
            catch (SoapHeaderException soapEx)
            {
                CarolLib.Log.Instance.Error("error in webservice GetContactGroupAsync", soapEx);
                MessageBox.Show("网络错误");
            }

            catch (Exception ex)
            {
                CarolLib.Log.Instance.Error("error in webservice GetAllTialsAndTypeAsync call back", ex);
                MessageBox.Show("未知错误");
            }
        }

        private void service_GetContactGroupCompleted(object sender, GetContactGroupCompletedEventArgs e)
        {
            try
            {
                companyList = e.Result.ToList<SMSContactGroup>();

                companyList.Insert(0, new SMSContactGroup() { GroupName = "--请选择--", GroupCode = "-1" });

                cbbCompany.DisplayMember = "GroupName";
                cbbCompany.ValueMember = "GroupCode";
                cbbCompany.DataSource = companyList;

            }

            catch (Exception ex)
            {
                CarolLib.Log.Instance.Error("error in webservice _GetContactGroup call back", ex);

                MessageBox.Show("未知错误");
            }

        }

        /// <summary>
        /// 创建树节点
        /// </summary>
        /// <param name="ListSource"></param>
        private void CreateTreeNode(List<PlaneType> ListSource)
        {
            treePlaneType.Nodes.Clear();

            TreeNode rootNode = new TreeNode("机型管理");
            rootNode.Name = "-1";
            rootNode.Tag = "root";
            rootNode.ContextMenuStrip = ctmRoot;

            List<PlaneType> parnetList = planeList.Where(f => f.ParentID == -1).ToList();

            foreach (PlaneType parentType in parnetList)
            {
                TreeNode parentNode = new TreeNode(parentType.TypeName);
                parentNode.Name = parentType.PlaneTypeID.ToString();
                parentNode.Tag = parentType;
                parentNode.ContextMenuStrip = ctmParent;

                //  parentNode.ExpandAll();

                List<PlaneType> childList = planeList.Where(f => f.ParentID == parentType.PlaneTypeID).ToList();

                foreach (PlaneType childType in childList)
                {
                    TreeNode childNode = new TreeNode(childType.TypeName);
                    childNode.Name = childType.PlaneTypeID.ToString();
                    childNode.Tag = childType;
                    childNode.ContextMenuStrip = ctmChild;

                    

                    foreach (ACARSDevice tail in childType.TailList)
                    {
                        TreeNode tialNode = new TreeNode(tail.TailNo);
                        tialNode.Name = tail.TailNo;
                        tialNode.Tag = tail;
                        tialNode.ContextMenuStrip = ctmPlane;

                        childNode.Nodes.Add(tialNode);
                    }

                    parentNode.Nodes.Add(childNode);
                }

                rootNode.Nodes.Add(parentNode);
            }

            rootNode.Expand();

            treePlaneType.Nodes.Add(rootNode);

        }

        private void BindParentDDL()
        {
            cbbPlaneType.DisplayMember = "TypeName";
            cbbPlaneType.ValueMember = "PlaneTypeID";
            cbbPlaneType.DataSource = planeList.Where(f => f.ParentID == -1).ToList();

            cbbPlaneType.Update();

            cbbPlaneType.SelectedIndex = 0;

            BindChildDDL();
        }

        private void BindChildDDL()
        {
            cbbChildType.DisplayMember = "TypeName";
            cbbChildType.ValueMember = "PlaneTypeID";
            List<PlaneType> source = planeList.Where(f => f.ParentID == Convert.ToInt32(cbbPlaneType.SelectedValue)).ToList();
            cbbChildType.DataSource = source;

            cbbChildType.Update();
        }

        #endregion

        #region 右击菜单
        private void addParentItem_Click(object sender, EventArgs e)
        {
            pnlType.Visible = btnSaveType.Visible = txtModelName.Enabled = txtDes.Enabled = true;
            pnPlane.Visible = lblParnet.Visible = txtEditParent.Visible = false;

            txtModelName.Text = txtDes.Text = "";

            txtModelName.Tag = "add";

            btnSaveType.Tag = -1;
        }

        private void editParnetItem_Click(object sender, EventArgs e)
        {
            pnlType.Visible = btnSaveType.Visible = txtModelName.Enabled = txtDes.Enabled = true;
            pnPlane.Visible = lblParnet.Visible = txtEditParent.Visible = false;


            txtModelName.Text = ((PlaneType)treePlaneType.SelectedNode.Tag).TypeName;
            txtModelName.Tag = "edit";
            txtDes.Text = ((PlaneType)treePlaneType.SelectedNode.Tag).Description;
            btnSaveType.Tag = ((PlaneType)treePlaneType.SelectedNode.Tag).PlaneTypeID;
        }

        private void deleteParentItem_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("此操作会删除本机型,子机型以及对应的机号,确定删除吗?", "提示", MessageBoxButtons.OKCancel))
            {
                //AuthService serviceProxy = service;


                serviceProxy.DeletePlaneTypeAsync(int.Parse(treePlaneType.SelectedNode.Name), "parent");
            }
        }

        private void addChildItem_Click(object sender, EventArgs e)
        {
            pnlType.Visible = btnSaveType.Visible = txtModelName.Enabled = txtDes.Enabled = lblParnet.Visible = txtEditParent.Visible = true;
            pnPlane.Visible = false;

            txtModelName.Text = txtDes.Text = "";
            txtModelName.Tag = "add";

            btnSaveType.Tag = ((PlaneType)treePlaneType.SelectedNode.Tag).PlaneTypeID;

            txtEditParent.Text = treePlaneType.SelectedNode.Text;
        }


        private void editChildItem_Click(object sender, EventArgs e)
        {
            pnlType.Visible = btnSaveType.Visible = txtModelName.Enabled = txtDes.Enabled = lblParnet.Visible = txtEditParent.Visible = true;
            pnPlane.Visible = false;


            txtModelName.Text = ((PlaneType)treePlaneType.SelectedNode.Tag).TypeName;
            txtModelName.Tag = "edit";
            txtDes.Text = ((PlaneType)treePlaneType.SelectedNode.Tag).Description;
            btnSaveType.Tag = ((PlaneType)treePlaneType.SelectedNode.Tag).PlaneTypeID;

            txtEditParent.Text = treePlaneType.SelectedNode.Parent.Text;

        }

        private void deleteChildItem_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("此操作会删除本机型以及对应的机号,确定删除吗?", "提示", MessageBoxButtons.OKCancel))
            {
                //AuthService serviceProxy = service;


                serviceProxy.DeletePlaneTypeAsync(int.Parse(treePlaneType.SelectedNode.Name), "child");
            }
        }

        private void addTailItem_Click(object sender, EventArgs e)
        {
            
        //    MessageBox.Show(ctmChild.Parent.Name);

            pnPlane.Visible = btnSavePlane.Visible = txtTail.Enabled = cbbCompany.Enabled = cbbPlaneType.Enabled = cbbChildType.Enabled = true;
            pnlType.Visible = false;

            txtTail.Text = "";
            txtTail.Tag = "add";

            PlaneType selectedType = (PlaneType)treePlaneType.SelectedNode.Tag;
            btnSavePlane.Tag = selectedType.PlaneTypeID;

            cbbPlaneType.SelectedValue = selectedType.ParentID;

            BindChildDDL();

            cbbChildType.SelectedValue = selectedType.PlaneTypeID;

            cbbCompany.SelectedIndex = 0;
        }

        private void editPlaneItem_Click(object sender, EventArgs e)
        {
            pnPlane.Visible = btnSavePlane.Visible = cbbCompany.Enabled = cbbPlaneType.Enabled = cbbChildType.Enabled = true;
            pnlType.Visible = txtTail.Enabled = false;

            txtTail.Text = ((ACARSDevice)treePlaneType.SelectedNode.Tag).TailNo;
            txtTail.Tag = "edit";
            cbbCompany.SelectedValue = ((ACARSDevice)treePlaneType.SelectedNode.Tag).CompanyCode;

            btnSavePlane.Tag = ((ACARSDevice)treePlaneType.SelectedNode.Tag).PlaneTypeID;

            try
            {
                cbbPlaneType.SelectedValue = int.Parse(treePlaneType.SelectedNode.Parent.Parent.Name);

                BindChildDDL();

                cbbChildType.SelectedValue = ((ACARSDevice)treePlaneType.SelectedNode.Tag).PlaneTypeID;
            }
            catch (Exception ex)
            {
                CarolLib.Log.Instance.Error(ex);
                MessageBox.Show("重新绑定数据错误");
            }

        }

        private void deletePlaneItem_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("确定删除本机号吗?", "提示", MessageBoxButtons.OKCancel))
            {
                //AuthService serviceProxy = service;


                serviceProxy.DeletePlaneInfoAsync(treePlaneType.SelectedNode.Name);
            }
        }
        #endregion

        #region button Click
        private void btnSaveType_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtModelName.Text))
            {
                MessageBox.Show("机型名称不能为空!");
                return;
            }

            PlaneType model = new PlaneType();
            model.TypeName = txtModelName.Text;
            model.Description = txtDes.Text;

            //AuthService serviceProxy = service;

            try
            {
                if (txtModelName.Tag.ToString() == "add")
                {
                    model.ParentID = int.Parse(btnSaveType.Tag.ToString());

                    serviceProxy.InsertPlaneTypeAsync(model);
                }
                else
                {
                    model.PlaneTypeID = int.Parse(btnSaveType.Tag.ToString());

                    serviceProxy.UpdatePlaneTypeAsync(model);
                }
            }
            catch (SoapException sex)
            {
                CarolLib.Log.Instance.Error(sex);
                MessageBox.Show("网络错误");
            }
            catch (Exception ex)
            {
                CarolLib.Log.Instance.Error(ex);
                MessageBox.Show("系统错误");
            }

        }


        private void btnSavePlane_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtTail.Text))
            {
                MessageBox.Show("机号不能为空!");
                return;
            }

            if (cbbChildType.SelectedValue == null)
            {
                MessageBox.Show("请选择机型!");
                return;
            }

            ACARSDevice model = new ACARSDevice();
            model.PlaneTypeID = int.Parse(btnSavePlane.Tag.ToString());
            model.TailNo = txtTail.Text;
            model.CompanyCode = cbbCompany.SelectedValue.ToString();
            model.PlaneTypeID = int.Parse(cbbChildType.SelectedValue.ToString());

            try
            {
                if (txtTail.Tag.ToString() == "add")
                {
                    serviceProxy.InsertPlaneInfoAsync(model);
                }
                else
                {
                    serviceProxy.UpdatePlaneInfoAsync(model);
                }
            }
            catch (SoapException sex)
            {
                CarolLib.Log.Instance.Error(sex);
                MessageBox.Show("网络错误");
            }
            catch (Exception ex)
            {
                CarolLib.Log.Instance.Error(ex);
                MessageBox.Show("系统错误");
            }
        }

        /// <summary>
        /// 右击节点时使该节点被选中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treePlaneType_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                treePlaneType.SelectedNode = e.Node;
            }
        }


        private void cbbPlaneType_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindChildDDL();
        }

        private void treePlaneType_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treePlaneType.SelectedNode.Level == 0)
            {
                pnlType.Visible = pnPlane.Visible = false;
            }
            else if (treePlaneType.SelectedNode.Level == 1)
            {
                pnPlane.Visible = txtDes.Enabled = txtModelName.Enabled = txtEditParent.Visible = lblParnet.Visible = btnSaveType.Visible = false;
                pnlType.Visible = true;

                PlaneType tag = (PlaneType)treePlaneType.SelectedNode.Tag;

                txtModelName.Text = tag.TypeName;
                txtDes.Text = tag.Description;


            }
            else if (treePlaneType.SelectedNode.Level == 2)
            {
                pnlType.Visible = txtEditParent.Visible = lblParnet.Visible = true;
                pnPlane.Visible = txtDes.Enabled = txtModelName.Enabled = btnSaveType.Visible = false;

                PlaneType tag = (PlaneType)treePlaneType.SelectedNode.Tag;

                txtModelName.Text = tag.TypeName;
                txtDes.Text = tag.Description;
                txtEditParent.Text = treePlaneType.SelectedNode.Parent.Text;
            }
            else if (treePlaneType.SelectedNode.Level == 3)
            {
                pnlType.Visible = btnSavePlane.Visible = txtTail.Enabled = cbbChildType.Enabled
                                = cbbCompany.Enabled = cbbPlaneType.Enabled = false;

                pnPlane.Visible = true;

                ACARSDevice tag = (ACARSDevice)treePlaneType.SelectedNode.Tag;

                txtTail.Text = tag.TailNo;
                cbbPlaneType.Text = treePlaneType.SelectedNode.Parent.Parent.Text;
                cbbChildType.Text = treePlaneType.SelectedNode.Parent.Text;
                cbbCompany.SelectedValue = tag.CompanyCode;

            }
        }


        #endregion

        #region webservice result
        private void service_InsertPlaneTypeCompleted(object sender, InsertPlaneTypeCompletedEventArgs e)
        {
            string result = e.Result;

            try
            {
                int TypeID = int.Parse(result);

                PlaneType type = new PlaneType();

                type.ParentID = int.Parse(btnSaveType.Tag.ToString());
                type.PlaneTypeID = TypeID;
                type.TypeName = txtModelName.Text;
                type.Description = txtDes.Text;

                planeList.Add(type);

                BindParentDDL();

                TreeNode node = new TreeNode(txtModelName.Text);

                node.Name = TypeID.ToString();
                node.Tag = type;
                node.ContextMenuStrip = treePlaneType.SelectedNode.ContextMenuStrip == ctmRoot ? ctmParent : ctmChild;

                treePlaneType.SelectedNode.Nodes.Add(node);

                treePlaneType.Update();

                txtModelName.Text = "";

                MessageBox.Show("保存成功");
            }
            catch
            {
                MessageBox.Show(result);
            }


        }

        private void service_UpdatePlaneTypeCompleted(object sender, UpdatePlaneTypeCompletedEventArgs e)
        {
            string result = e.Result;

            if (string.IsNullOrEmpty(result))
            {
                //int TypeID = int.Parse(result);

                PlaneType type = (PlaneType)treePlaneType.SelectedNode.Tag;

                type.TypeName = txtModelName.Text;
                type.Description = txtDes.Text;
                treePlaneType.SelectedNode.Tag = type;
                treePlaneType.SelectedNode.Text = txtModelName.Text;

                treePlaneType.Update();

                try
                {
                    planeList.Where(f => f.PlaneTypeID == type.PlaneTypeID).ToList()[0].TypeName = txtModelName.Text;

                    BindParentDDL();
                }
                catch (Exception ex)
                {
                    CarolLib.Log.Instance.Error(ex);
                    MessageBox.Show("更新客户端数据错误");
                    return;
                }

                MessageBox.Show("保存成功");
            }
            else
            {
                MessageBox.Show(result);
            }
        }

        private void service_InsertPlaneInfoCompleted(object sender, InsertPlaneInfoCompletedEventArgs e)
        {

            if (string.IsNullOrEmpty(e.Result))
            {
                ACARSDevice model = new ACARSDevice();

                model.TailNo = txtTail.Text;
                model.PlaneTypeID = int.Parse(cbbChildType.SelectedValue.ToString());
                model.CompanyCode = cbbCompany.SelectedValue.ToString();

                TreeNode node = new TreeNode(txtTail.Text);
                node.Name = txtTail.Text;
                node.Tag = model;
                node.ContextMenuStrip = ctmPlane;
                //  treePlaneType.SelectedNode.Nodes.Add(node);

                TreeNode[] nodes = treePlaneType.Nodes.Find(cbbChildType.SelectedValue.ToString(), true);

                if (nodes != null && nodes.Count() == 1)
                {
                    nodes[0].Nodes.Add(node);
                }

                txtTail.Text = "";
                cbbCompany.SelectedIndex = 0;

                MessageBox.Show("保存成功");
            }
            else
            {
                MessageBox.Show(e.Result);
            }

        }

        private void service_UpdatePlaneInfoCompleted(object sender, UpdatePlaneInfoCompletedEventArgs e)
        {
            if (string.IsNullOrEmpty(e.Result))
            {

                TreeNode node = treePlaneType.SelectedNode;
                ACARSDevice model = (ACARSDevice)node.Tag;

                model.PlaneTypeID = int.Parse(cbbChildType.SelectedValue.ToString());
                model.CompanyCode = cbbCompany.SelectedValue.ToString();
                node.Tag = model;

                TreeNode[] nodes = treePlaneType.Nodes.Find(model.PlaneTypeID.ToString(), true);

                if (nodes == null || nodes.Length != 1)
                {
                    MessageBox.Show("更新客户端数据错误");
                    return;
                }
                else
                {
                    try
                    {
                        treePlaneType.SelectedNode.Parent.Nodes.Remove(node);

                        nodes[0].Nodes.Add(node);
                    }
                    catch (Exception ex)
                    {
                        CarolLib.Log.Instance.Error("error in update client Data", ex);

                        MessageBox.Show("更新客户端数据错误");

                        return;
                    }
                }

                MessageBox.Show("保存成功");
            }
            else
            {
                MessageBox.Show(e.Result);
            }
        }

        private void service_DeletePlaneTypeCompleted(object sender, DeletePlaneTypeCompletedEventArgs e)
        {
            if (e.Result)
            {
                treePlaneType.Nodes.Remove(treePlaneType.SelectedNode);

                MessageBox.Show("删除成功");
            }
            else
            {
                MessageBox.Show("删除失败");
            }
        }

        private void service_DeletePlaneInfoCompleted(object sender, DeletePlaneInfoCompletedEventArgs e)
        {
            if (e.Result)
            {
                treePlaneType.Nodes.Remove(treePlaneType.SelectedNode);

                MessageBox.Show("删除成功");
            }
            else
            {
                MessageBox.Show("删除失败");
            }
        }

        #endregion

       
       
       
    }
}
